<template>
  <!-- 质量整改通知单业务待办 -->
  <base-breadcrumb :title="$route.meta.title">
    <a-spin :spinning="loading">
      <!-- 问题信息 -->
      <a-card :bordered="false">
        <title-name title="处理"></title-name>
        <div class="ml12">
          <title-name title="补充整改通知单信息"></title-name>
          <!-- 表格 -->
          <a-table rowKey="sort" bordered ref="table" row-key="id" :columns="columns" :dataSource="form.checks" :pagination="false" class="mb20">
            <template slot="rectifierCompanyName" slot-scope="text, record, index">
              {{setRectifierCompanyName(record)}}
            </template>
            <!-- 操作栏 -->
            <more-button slot="action" slot-scope="text, record, index">
              <a @click="handleManage(record)">补充</a>
              <a v-if="index != 0" @click="handleCompensate(record, index)">自动填充</a>
            </more-button>
            <!-- 现场图片 -->
            <l-table slot="fileArrays" uploadType="image" editModel="V" slot-scope="text" :upload-arrys="text" :disabled="true" isUploadImgAndVideo />
          </a-table>
          <!-- 操作栏 -->
          <div class="btn_box" align="right">
            <a-button type="primary" @click="handleSubmit">确认处理</a-button>
          </div>
        </div>
        <!-- 补充问题信息弹窗 -->
        <DialogProblem ref="dialogEditModel" headerTitle="补充问题信息" :dialogEditModel="dialogEditModel" @confirm="handleConfirm" :dialogForm="dialogForm" :rules="rules" @emptyRules="emptyRules" @changeCheckTypeId="changeCheckTypeId"/>
      </a-card>
      <!-- 业务详情 -->
      <a-card :bordered="false">
        <h1>业务详情</h1>
        <title-name title="基础信息"></title-name>
        <!-- 表单信息 -->
        <CustomForm ref="ruleForm" isValidate :formList="formList" :form="form" editModel="V" :isEmit="false" />
      </a-card>
    </a-spin>
    <div class="btn_box tool-btns--fixed page-btn-right-top">
       <a-button type="primary" @click="$close">关闭</a-button>
     </div>
  </base-breadcrumb>
</template>

<script>
import { STable } from '@/components' // 表格
import { rectificationNotice } from '@/api/quality/quality' // 质量api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BasePrintButton from '@/components/BasePrintButton' // 打印按钮
import SelectTreeOrg from '@/components/Select/SelectTreeOrg' // 组织机构
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople' // 人员选择器
import MoreButton from '@/components/MoreButton' // 多按钮容器
import DialogProblem from './components/DialogProblem' // 添加问题弹窗
const columns = [
  {
    title: '序号',
    dataIndex: 'sort',
    width: 60,
    align: 'center'
  },
  {
    title: '检查类别',
    // ellipsis: true,
    dataIndex: 'checkTypeName'
  },
  {
    title: '分部分项',
    // ellipsis: true,
    dataIndex: 'subProjectName'
  },
  {
    title: '检查区域',
    // ellipsis: true,
    dataIndex: 'respAreaName'
  },
  {
    title: '检查部位',
    // ellipsis: true,
    dataIndex: 'checkDescribe'
  },
  {
    title: '影像资料',
    width: 110,
    dataIndex: 'fileArrays',
    scopedSlots: { customRender: 'fileArrays' }
  },
  {
    title: '问题描述',
    // ellipsis: true,
    dataIndex: 'problemTypeName'
  },
  {
    title: '问题补充',
    // ellipsis: true,
    dataIndex: 'description'
  },
  {
    title: '整改单位',
    // ellipsis: true,
    dataIndex: 'rectifierCompanyName',
   scopedSlots: { customRender: 'rectifierCompanyName' }
  },
  {
    title: '责任人',
    dataIndex: 'dutyName'
  },
  {
    title: '整改人',
    dataIndex: 'rectifierName'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '180px',
    // fixed: 'right',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    STable,
    BasePrintButton,
    MoreButton,
    DialogProblem
  },
  data() {
    this.columns = columns // 问题信息表格表头
    return {
      loading: false, // 请求加载框
      statusCode: '', // 审批状态
      editModel: '0', // 操作类型：0 新增，1 编辑，2 查看
      dialogEditModel: 'E', // 弹窗操作类型：U 新增；E 编辑
      form: {
        // 表单
        checks: [], // 问题信息表格列表
        creatorName: void 0, // 下发人
        createTime: void 0 // 下发时间
      },
      dialogForm: {}, //弹窗表单
      rules: {
        // 弹窗表单校验规则
        checkTypeId: [{ required: true, message: '请选择检查类别', trigger: 'change' }],
        typeId: [{ required: true, message: '请选择检查类型', trigger: 'change' }],
        subProjectId: [{ required: true, message: '请选择分部分项', trigger: 'change' }],
        respAreaId: [{ required: true, message: '请选择检查区域', trigger: 'change' }],
        problemTypeId: [{ required: true, message: '请选择质量问题描述', trigger: 'change' }],
        levelName: [{ required: true, message: '请选择问题级别', trigger: 'change' }],
        areaId: [{ required: true, message: '请选择整改单位', trigger: 'change' }],
        rectifierId: [{ required: true, message: '请选择整改人', trigger: 'change' }],
        dutyId: [{ required: true, message: '请选择责任人', trigger: 'change' }],
        reCheckId: [{ required: true, message: '请选择复查人', trigger: 'change' }],
        coordinate: [{ type: 'array', required: true, message: '请选择检查（问题）具体位置', trigger: 'change' }],
        fileArrays: [{ type: 'array', required: true, message: '请选择影像资料', trigger: 'change' }],
        description: [{ required: true, message: '请输入质量问题补充' }],
      }
    }
  },
  mounted() {
    // 请求业务详情
    this.init()
  },
  computed: {
    // 只读模式
    onlyRead() {
      return this.editModel == 2 || this.editModel == 3
    },
    // 表单配置项
    formList() {
      return [
        {
          keyName: 'receivingUnit',
          label: '接收单位',
          type: 'BaseInput',
          rule: {
            required: true,
            whitespace: true,
            message: '请输入接收单位',
            trigger: 'change'
          }
        },
        {
          keyName: 'receivingEmployee',
          label: '接收人',
          type: 'BaseInput',
          rule: {
            required: true,
            whitespace: true,
            message: '请输入接收人',
            trigger: 'change'
          }
        },
        {
          keyName: 'inspectedUnitId',
          viewName: 'inspectedUnitName',
          label: '受检单位',
          type: SelectTreeOrg,
          attrs: {
            returnFindItem: true,
            parentDisabled: true
          },
          rule: {
            required: true,
            whitespace: true,
            message: '请输入受检单位',
            trigger: 'change'
          },
          selectChange: (e) => {
            // 添加项目id到表单
            this.form.projectId = e.projectId
            this.form.inspectedUnitName = e.orgName
          }
        },
        {
          keyName: 'supplementEmployeeId',
          viewName: 'supplementEmployeeName',
          label: '补充信息人员',
          type: ASelectOrgPeople,
          attrs: {
            customRender: null,
            keyValue: 'inspectedUnitId', // 联动字段名
            form: this.form, // 联动表单
            init: false // 取消数据初始化，根据受检单位请求人员
          },
          rule: {
            required: true,
            message: '请选择入补充信息人员',
            trigger: 'change'
          }
        },
        {
          keyName: 'creatorName',
          label: '下发人',
          type: 'BaseInput',
          disabled: true
        },
        {
          keyName: 'createTime',
          label: '下发时间',
          type: 'BaseInput',
          disabled: true
        },
        {
          keyName: 'basicSituation',
          label: '基本情况',
          type: 'BaseTextarea',
          span: 24,
          rule: {
            required: true,
            whitespace: true,
            message: '请输入基本情况',
            trigger: 'change'
          }
        },
        {
          keyName: 'rectifyTerm',
          label: '整改期限',
          type: 'a-date-picker',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          },
          rule: {
            required: true,
            message: '请选择整改期限',
            trigger: 'change'
          }
        },
        {
          keyName: 'acceptanceEmployeeId',
          label: '验证人',
          type: 'SelectPerson',
          isSingle: true,
          span: 16,
          rule: {
            required: true,
            message: '请选择验证人',
            trigger: 'change'
          }
        },
        {
          keyName: 'sendUser',
          label: '抄送人',
          type: 'SelectPerson',
          isSingle: true,
          span: 16,
          rule: {
            required: true,
            message: '请选择验证人',
            trigger: 'change'
          }
        }
      ]
    },
    validateList() {
      return [
        {
          type: 'a-select',
          label: '验证结果',
          keyName: 'status',
          viewName: 'statusName',
          data: [
            {
              value: 'QUALIFIED',
              label: '合格'
            },
            {
              value: 'UNQUALIFIED',
              label: '不合格'
            }
          ],
          rule: {
            required: true,
            message: '请选择验证结果',
            trigger: 'change'
          }
        }
      ]
    },
  },
  methods: {
    /**
     * @description: 请求业务详情
     */
    init() {
      this.loading = true
      rectificationNotice
        .dealt({
          id: this.id
        })
        .then((res) => {
          if (res.data) {
            // 将checks里的problem扁平到checks
            res.data.checks = res.data.checks?.length
              ? res.data.checks.map((i, index) => {
                  i.sort = index + 1
                  // 格式化坐标
                  i.problem.coordinate =
                    i.problem.coordinate?.split(';')?.map((e) => {
                      const item = e.split(',')
                      return {
                        x: item[0],
                        y: item[1]
                      }
                    }) || []
                  // 格式化工程品质类型
                  if (i.specialName) {
                    i.specialTypes = [i.specialType, i.specialName]
                  }
                  return { ...i.problem, ...i }
                })
              : []
            // 格式化验证人
            if (res.data.acceptanceEmployeeId) {
              res.data.acceptanceEmployeeId = [{ id: res.data.acceptanceEmployeeId, name: res.data.acceptanceEmployeeName }]
            }

            this.form = res.data
            // 若是编辑，则把下发人和下发时间替换
            if (this.editModel === 1) {
              this.form.creatorName = this.$userInfo()?.name
              this.form.createTime = this.$dateFormat(new Date(), 'D')
            }
            //是项目的管理行为和工程资料，把整改单位取受检单位
            this.form.checks.map((item)=>item.inspectedUnitName = res.data.inspectedUnitName)
            // 框架bug，表格右侧操作列固定右侧，高度不会随同行高度自适应，需要手动更新
            this.$nextTick(() => {
              setTimeout(() => {
                this.$forceUpdate()
              }, 500)
            })
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    //设置整改单位
    setRectifierCompanyName(data){
      let rectifierCompanyName = null;
      if(data.checkTypeName == '工程实体' || data.checkTypeName == '工程措施'){   //是这两个类型就取table带出的，否则就是受检单位
          rectifierCompanyName = data.rectifierCompanyName;
      }else{
        rectifierCompanyName = data.inspectedUnitName;
      }
      return rectifierCompanyName;
    },
    /**
     * @description:
     * @param {*} record：业务对象
     */
    handleManage(record) {
      // 因为弹窗表单里的分部分项表单是根据项目id请求的数据，所以必须先校验项目id,
      // if (!this.form.projectId || !record.inspectedUnitId) {
      //   // 项目id来自于受检单位项目部的选择
      //   this.$message.warning('请先选择受检单位')
      //   return
      // }
      if (!this.form.rectifyTerm) {
        this.$message.warning('请先选择整改期限！')
        return
      }
       let findData = this.form.checks.find((item)=>item.id === record.id); //解决缓存问题。
      this.dialogForm = { projectId: this.form.projectId, inspectedUnitId: this.form.inspectedUnitId, ...findData,inspectedUnitName:this.form.inspectedUnitName}
      this.$refs.dialogEditModel.visible = true
      this.dialogForm.tageCode = this.form.projectId?'PD':'BC';   // 补充是项目就传PD
      this.dialogForm.projectTypeId =findData.projectTypeId;
      this.dialogForm.newRespAreaId = this.dialogForm.respAreaId;
      this.dialogForm.isBcRules = true; //这是用来判断是不是补充
      // this.dialogForm.inspectedUnitName = this.form.projectId?null:this.form.inspectedUnitName;
      this.setRules(true);
    },
    emptyRules(val){
      if(val){
        this.$nextTick(()=>{
         this.setRules(false);
     })
      }
    },
     setRules(falg){
        this.$set(this.rules,'respAreaId',[{ required: falg, message: '请选择检查区域', trigger: 'change' }])
        this.$set(this.rules,'subProjectId',[{ required: falg, message: '请选择分部分项', trigger: 'change' }])
        this.$set(this.rules,'coordinate',[{ required: falg, message: '请选择检查（问题）具体位置', trigger: 'change' }])
        this.$set(this.rules,'fileArrays',[{ type: 'array', required: falg, message: '请选择影像资料', trigger: 'change' }],)
        this.$set(this.rules,'areaId',[{ required: falg, message: '请选择整改单位', trigger: 'change' }],)

    },
    /**
     * @description: 操作表单到表格
     * @param {*} form：表单
     */
    handleConfirm(form) {
      // 新增操作
      if (this.dialogEditModel === 'U') {
        form.sort = this.form.checks.length + 1
        this.form.checks.push(form)
      } else {
        //编辑
        // 有sort说明是前端数据，有id则为后端数据
        if (form.sort) {
          this.form.checks.splice(form.sort - 1, 1, form)
        } else if (form.id) {
          let sort = this.form.checks.findIndex((i) => i.id === form.id)
          this.form.checks.splice(sort - 1, 1, form)
        }
      }
      // 框架bug，表格右侧操作列固定右侧，高度不会随同行高度自适应，需要手动更新
      // this.refreshTable()
      this.$refs.dialogEditModel.visible = false
    },
    /**
     * @description: 自动补充
     * @param {*} record：业务对象
     * @param {*} index：索引值
     */
    handleCompensate(record, index) {
      let preItem = this.form.checks[index - 1] // 上条数据
      if (record.subProjectId && preItem.subProjectId !== record.subProjectId) {
        this.$message.warning('上条数据的分部分项与本条不一致，不能填充')
        return
      }
      if (record.rectifierCompanyId && preItem.rectifierCompanyId !== record.rectifierCompanyId) {
        this.$message.warning('上条数据的整改单位与本条不一致，不能填充')
        return
      }
      if (record.respAreaId && preItem.respAreaId !== record.respAreaId) {
        this.$message.warning('上条数据的检查区域与本条不一致，不能填充')
        return
      }
      if (record.checkTypeId && preItem.checkTypeId !== record.checkTypeId) {
        this.$message.warning('上条数据的检查类别与本条不一致，不能填充')
        return
      }
      // 填充上一条的数据到本条对应空白处
      for (let key in record) {
        // 当本条数据的字段没值，且上条数据该字段有值则填充
        if ((!record[key] || (key === 'coordinate' && !record[key]?.length)) && preItem[key]) {
          record[key] = preItem[key]
        }
        // coordinate在problem对象里面，需要单独判断
        console.log(key, record[key]?.coordinate, preItem[key]?.coordinate)
        if (key === 'problem' && !record[key].coordinate?.length && preItem[key].coordinate) {
          this.$set(record[key], 'coordinate', preItem[key].coordinate)
        }
      }
      // 框架bug，表格右侧操作列固定右侧，高度不会随同行高度自适应，需要手动更新
      // this.refreshTable()
    },
    /**
     * @description: 框架bug，表格右侧操作列固定右侧，高度不会随同行高度自适应，需要手动更新
     * @return {*}
     */
    // refreshTable() {
    //   this.$nextTick(() => {
    //     setTimeout(() => {
    //       this.$forceUpdate()
    //     }, 500)
    //   })
    // },
    /**
     * @description: 处理
     * @return {*}
     */
    handleSubmit() {
      let that = this
      // 提交表单
      let form = that.$clone(that.form)
       if(Array.isArray(that.form.sendUserIds) && that.form.sendUserIds?.length){
        form.sendUserIds = that.form.sendUserIds.join(',');   //后端返回的是数组，要传给后端字符串
      }
      // 整改通知单提交前处理
      if (form.checks?.length) {
        const transferNames = ['problemTypeId', 'description', 'levelName', 'rectifierCompanyId', 'rectifierId', 'dutyId', 'reCheckId', 'sendUserIds', 'rectifyTerm'] // 需要处理的表单列表
        // 遍历整改通知单
        for (let index in form.checks) {
          let item = form.checks[index] // 通知单业务对象
          // 转译打点坐标
          if (Array.isArray(item.problem?.coordinate)) {
            item.problem.coordinate = item.problem.coordinate?.map((i) => i.x + ',' + i.y)?.join(';')
          }
            if(item.checkTypeName=='管理行为' || item.checkTypeName=='工程资料'){
              this.setRules(false)
            }else{
              this.setRules(true)
            }
            item.rules = this.rules
            for(let rulesKey in item.rules){  // 删除手动设置不需要校验的字段
              !item.rules[rulesKey][0].required && delete item.rules[rulesKey]
            }
            item.checkNames = Object.keys(item.rules) // 需要校验的表单列表
            if(!item.coordinate || item.coordinate?.length<1){  //后端返回的是空数组，需要特殊校验处理
              item.coordinate = null;
            }
            if(item.description || item.problemTypeId){   //问题描述和问题补充只有验证一个就行
              item.checkNames = item.checkNames.filter((itemName,index)=>{
            return itemName != 'description' && itemName !='problemTypeId';
            })
            }
            console.log(item,1)
          // 遍历业务对象，校验需要校验的表单
          for (let key in item) {
            if (item.checkNames.includes(key) && !item[key]) {
              this.$message.warning(`第${Number(index) + 1}条通知单${this.rules[key]?.[0]?.message}`)
              return
            }
          }
          // 将form.checks中需要处理的表单放进problem，且删除根对象相应表单
          for (let name of transferNames) {
            if (item[name]) {
              item.problem[name] = item[name]
              delete item[name]
            }
          }
        }
      } else {
        this.$message.warning('问题信息列表不能为空！')
        return
      }
      // 格式化验证人
      if (form.acceptanceEmployeeId) {
        form.acceptanceEmployeeId = form.acceptanceEmployeeId[0]?.id
      }
      if(form?.checks?.length){    //删除手动设置的校验
        form.checks.map((item)=>{
          delete item.rules;
          delete item.checkNames;
          // delete item.inspectedUnitId;
          // delete item.inspectedUnitName;
        })
      }
      that.$confirm({
        titile: '提示',
        content: '确认处理，处理后不可撤回？',
        onOk: () => {
          return rectificationNotice.supplement(form).then((res) => {
            if (res.code === 200 || res.data.code === 200) {
              that.$message.success('处理成功！')
              that.$multiTab.close()
            }
          })
        }
      })
    },
    changeCheckTypeId(val){  //监听检查类别的变化，来改变校验信息
      this.setRules(!val)
      console.log(this.rules)
    }
  }
}
</script>